package cn.congine.wizarpos.mall.action;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import cn.congine.wizarpos.mall.common.RespMessage;
import cn.congine.wizarpos.mall.model.ErpProduct;
import cn.congine.wizarpos.mall.model.open.AddToShoppingCartInput;
import cn.congine.wizarpos.mall.model.open.AddToShoppingCartOutput;
import cn.congine.wizarpos.mall.model.open.GetShoppingCartItemNumInput;
import cn.congine.wizarpos.mall.model.open.GetShoppingCartItemNumOutput;
import cn.congine.wizarpos.mall.model.open.Merchandise;
import cn.congine.wizarpos.mall.model.open.MerchandiseSyncInput;
import cn.congine.wizarpos.mall.model.open.MerchandiseSyncOutput;
import cn.congine.wizarpos.mall.service.impl.WizarposOpenRestClient;
import cn.congine.wizarpos.mall.utils.Function;
import cn.congine.wizarpos.mall.utils.SysConstants;

@Controller
@RequestMapping(value = "/erp_product")
public class ErpProductAction {

	private static Logger logger = Logger.getLogger(ErpProductAction.class);
	
//	@Autowired
//	private ErpProductService erpProductService;
//
//	@Autowired
//	private ErpProductStockService erpProductStockService;
//	
//	@Autowired
//	private ErpProductPicDefService erpProductPicDefService;
//
//	@Autowired
//	private SysMerchantDefService sysMerchantDefService;
//
//	@Autowired
//	private WxShoppingCartItemService wxShoppingCartItemService;
//
//	@Autowired
//	private WxShoppingCartService wxShoppingCartService;

	@Autowired
	private WizarposOpenRestClient wizarposOpenRestClient;
	
/*	@RequestMapping(value = "/get")
	public ModelAndView getErpProduct(@RequestParam(value = "id") String id,
			@RequestParam(value = "openId") String openId, Model model) {
		Map<String, Object> data = new HashMap<String, Object>();
		Map<String, Object> erp = new HashMap<String, Object>();
		Map<String, Object> erpPro = new HashMap<String, Object>();
		logger.info(">>>>商品详情页 商品id" + id + " openId:" + openId);
		ErpProduct erpP = erpProductService.getErpProductById(id);
		if (erpP == null) {
			data.put("err_message", "该商品不存在");
			return new ModelAndView("error", data);
		}
		
		String mid = erpP.getMid();
		// set stock of this product for show
		Integer stock = erpProductStockService.getTotalStock(mid, id);
		erpP.setStock(stock);
		
		WxShoppingCart cart = wxShoppingCartService.getWxShoppingCart(openId, mid);
		if (cart == null) {
			cart = new WxShoppingCart();
			cart.setCartType("1");
			cart.setCreateTime(System.currentTimeMillis());
			cart.setMid(mid);
			cart.setOpenId(openId);
			wxShoppingCartService.save(cart);
			cart = wxShoppingCartService.getWxShoppingCart(openId, mid);
		}

		List<cn.congine.wizarpos.mall.vo.WxShoppingCartItem> items = wxShoppingCartItemService
				.getWxShoppingCartItemListByCartId(cart.getId());
		int total = 0;
		for (cn.congine.wizarpos.mall.vo.WxShoppingCartItem item : items) {
			total = total + item.getProductNum();
		}
		// int total= wxShoppingCartItemService.getItemsNum(cart.getId());

		String price = Utils.formatAmount(erpP.getPrice());
		erp.put(erpP.getId(), price);
		String memberPrice = Utils.formatAmount(erpP.getMemberPrice());
		if (null != erpP.getPicId() && !erpP.getPicId().equals("")) {
			String picIds[] = erpP.getPicId().split(",");
			if (picIds.length > 0) {
				// 注意id为空的情况
				if (erpProductPicDefService.getErpProductPicDefById(picIds[0]) != null)
					erpP.setPicUrl(Function.dealGridPicUrl(
							erpProductPicDefService.getErpProductPicDefById(
									picIds[0]).getAddress(), 300, 300));
			}
		} else {
			erpP.setPicUrl(SysConstants.DEFAULT_PICTURE_DETAIL);
		}
		logger.info("当前购物车数量：" + total);
		erpPro.put(erpP.getId(), memberPrice);

		data.put("erpPro", erpPro);
		data.put("erp", erp);
		data.put("erpProduct", erpP);
		data.put("mid", mid);
		data.put("openId", openId);
		data.put("total", total);
		return new ModelAndView("product/detail", data);
	}*/
	
	@RequestMapping(value = "/get")
	public ModelAndView getErpProduct(@RequestParam(value = "id") String id,
			@RequestParam(value = "mid") String mid,//add xudongdong
			@RequestParam(value = "openId") String openId, Model model) {
		Map<String, Object> data = new HashMap<String, Object>();
		Map<String, Object> erp = new HashMap<String, Object>();
		Map<String, Object> erpPro = new HashMap<String, Object>();
		
		//请求开放平台接口，获取商品信息
		MerchandiseSyncInput merchandiseSyncInput = new MerchandiseSyncInput();		
		merchandiseSyncInput.setMid(mid);
		merchandiseSyncInput.setProductId(id);
		MerchandiseSyncOutput merchandiseSyncOutput = (MerchandiseSyncOutput) wizarposOpenRestClient.post(merchandiseSyncInput, "/product/merchandise", MerchandiseSyncOutput.class);		
		List<Merchandise> productList = merchandiseSyncOutput.getResult();		
		if (productList == null || productList.size() == 0) {
			data.put("err_message", "该商品不存在");
			return new ModelAndView("error", data);			
		}
		Merchandise product = productList.get(0);
		ErpProduct erpP = new ErpProduct();		
		try {
			BeanUtils.copyProperties(erpP, product);
		} catch (IllegalAccessException | InvocationTargetException e) {
			//do nothing
		}
		erpP.setId(product.getProductId());
		erpP.setStock(product.getStock());

		int total = 0;
		GetShoppingCartItemNumInput input = new GetShoppingCartItemNumInput();
		input.setMid(mid);
		input.setOpenId(openId);
		GetShoppingCartItemNumOutput output = (GetShoppingCartItemNumOutput) wizarposOpenRestClient.post(input, "/wxshop/get_cart_item_num", GetShoppingCartItemNumOutput.class);		
		total = output.getNum();
		erp.put(erpP.getId(), erpP.getPrice());
		if ("".equals(product.getPicUrl())) {
			erpP.setPicUrl(SysConstants.DEFAULT_PICTURE_DETAIL);
		} else {
			erpP.setPicUrl(Function.dealGridPicUrl(product.getPicUrl(), 300, 300));
		}		

		erpPro.put(erpP.getId(), product.getMemberPrice().toString());

		data.put("erpPro", erpPro);
		data.put("erp", erp);
		data.put("erpProduct", erpP);
		data.put("mid", mid);
		data.put("openId", openId);
		data.put("total", total);

		return new ModelAndView("product/detail", data);
	}	

/*	*//**
	 * 把商品加入到购物车
	 * 
	 * @param productId
	 * @param openId
	 * @param mid
	 * @param productPrice
	 * @return
	 *//*
	@RequestMapping(value = "/addToShoppingCart", method = RequestMethod.POST)
	@ResponseBody
	public RespMessage addToShoppingCart(
			@RequestParam(value = "productId") String productId,
			@RequestParam(value = "openId") String openId) {
		Map<String, Object> data = new HashMap<String, Object>();
		logger.info("添加商品到购物车 productId" + productId + " openId:" + openId);
		RespMessage resp = new RespMessage();
		ErpProduct product = erpProductService.getErpProductById(productId);
		if (product == null) {
			data.put("err_message", "该商品已下架");
			resp.setCode(1);
			resp.setMessage("该商品已下架");
			return resp;
		}
		
		String mid = product.getMid();
		SysMerchantDef merchantDef = (SysMerchantDef) sysMerchantDefService
				.getSysMerchantDefByMid(mid);
		if (merchantDef == null) {
			data.put("err_message", "该商户不存在");
			resp.setCode(1);
			resp.setMessage("该商户不存在");
			return resp;
		}
		
		WxShoppingCart wxshoppingcart = wxShoppingCartService
				.getWxShoppingCart(openId, mid);
		if (wxshoppingcart == null) {
			wxshoppingcart = new WxShoppingCart();
			wxshoppingcart.setCartType("1");
			wxshoppingcart.setCreateTime(System.currentTimeMillis());
			wxshoppingcart.setMid(mid);
			wxshoppingcart.setOpenId(openId);
			wxShoppingCartService.save(wxshoppingcart);
			wxshoppingcart = wxShoppingCartService
					.getWxShoppingCart(openId, mid);
		}
		// 首先判断购物车是否有这个商品
		Boolean result = wxShoppingCartItemService.checkItemsExist(productId,
				wxshoppingcart.getId());
		if (result) {
			// 获取购物车中该商品的数量
			int num = wxShoppingCartItemService.getItemNum(
					wxshoppingcart.getId(), productId);
			// 更新购物车中的物品数量
			num = num + 1;
			// 更新购物车中的物品数量
			wxShoppingCartItemService.updateNum(num, wxshoppingcart.getId(), productId, merchantDef.getMid());
		} else {
			WxShoppingCartItem items = null;
			if (product.getMemberPrice() != null) {
				items = new WxShoppingCartItem(merchantDef.getMid(), wxshoppingcart.getId(),
						productId, 1, product.getMemberPrice());
			} else if (product.getPrice() != null) {
				items = new WxShoppingCartItem(merchantDef.getMid(), wxshoppingcart.getId(),
						productId, 1, Integer.valueOf(product.getPrice()));
			} else {
				logger.error("保存商品失败！ 商品未设置价格 ");
				resp.setCode(1);
				resp.setMessage("保存商品失败！");
				return resp;
			}
			try {
				wxShoppingCartItemService.save(items);
				resp.setCode(0);
				resp.setMessage("添加商品成功！");
				logger.info("加入购物车成功：" + items.toString());
				return resp;
			} catch (Exception e) {
				logger.error("保存商品失败！ cased By:", e);
				resp.setCode(1);
				resp.setMessage("保存商品失败！");
				return resp;
			}
		}

		return resp;
	}*/
	
	/**
	 * 把商品加入到购物车
	 * 
	 * @param productId
	 * @param openId
	 * @param mid
	 * @param productPrice
	 * @return
	 */
	@RequestMapping(value = "/addToShoppingCart", method = RequestMethod.POST)
	@ResponseBody
	public RespMessage addToShoppingCart(
			@RequestParam(value = "productId") String productId, //add String mid,
			@RequestParam(value = "openId") String openId) {
		RespMessage resp = new RespMessage();		
		//请求开放平台接口，添加商品到购物车	
		AddToShoppingCartInput addToShoppingCartInput = new AddToShoppingCartInput();	
		addToShoppingCartInput.setOpenId(openId);
		addToShoppingCartInput.setProductId(productId);
		AddToShoppingCartOutput output = (AddToShoppingCartOutput) wizarposOpenRestClient.post(addToShoppingCartInput, "/wxshop/addToShoppingCart", AddToShoppingCartOutput.class);
		
		if ("0".equals(output.getCode())) {
			resp.setCode(0);
			resp.setMessage("添加商品成功！");
			return resp;			
		} else if ("60022".equals(output.getCode())) { //非法商品编号:
			resp.setCode(1);
			resp.setMessage("该商品已下架");
			return resp;		
		} else if ("60001".equals(output.getCode())) {//非法慧商户号
			resp.setCode(1);
			resp.setMessage("该商户不存在");
			return resp;			
		} else if ("60058".equals(output.getCode())) {//商品未设置价格
			resp.setCode(1);
			resp.setMessage("保存商品失败！");
			return resp;			
		} else if ("60019".equals(output.getCode())) {//非微信会员，无会员卡，前往会员卡领取页面
			resp.setCode(2);
			resp.setMessage("请先领取会员卡，再购买商品！");
			return resp;			
		} else {
			resp.setCode(1);
			resp.setMessage("保存商品失败！");
			return resp;			
		}		
	}
}
